package com.rtf.framework.web.mvc.rest.dict.dto;


import com.google.common.base.Predicates;
import com.rtf.framework.common.dto.support.DTOCallbackHandlerAdaptor;
import com.rtf.framework.common.util.UtilCollection;
import com.rtf.framework.common.util.UtilMap;
import com.rtf.framework.common.util.UtilReflection;
import com.rtf.framework.common.util.UtilString;
import com.rtf.framework.web.mvc.rest.dict.SysDictService;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.reflections.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Setter
@Getter
@Slf4j
@Service
public class DtoCallbackHandlerWithDict extends DTOCallbackHandlerAdaptor {

    //转换后字典项的后缀
    private String postfix = "_dict";

    @Autowired
    private SysDictService sysDictService;

    public void preHandle(List<Map<String, Object>> dtoMapList, Class<?> itemClass) {
        if (UtilCollection.isEmpty(dtoMapList)) {
            return;
        }
        //查询字典项
        Set<Field> dictFields = UtilReflection.getAllFields(itemClass, Predicates.and(ReflectionUtils.withAnnotation(DictField.class)));
        if (UtilCollection.isEmpty(dictFields)) {
            return;
        }
        for (Field dictField : dictFields) {
            DictField dictFieldAnon = dictField.getAnnotation(DictField.class);
            if (dictFieldAnon == null || UtilString.isBlank(dictFieldAnon.value())) {
                continue;
            }
            formatDict(dictField.getName(), dictFieldAnon.value(), dtoMapList);
        }

    }

    /**
     * 添加每个字段的字典编码值
     *
     * @param fieldName
     * @param dictCode
     * @param dtoMapList
     */
    private void formatDict(String fieldName, String dictCode, List<Map<String, Object>> dtoMapList) {
        Map<String, String> dictKv = sysDictService.queryChildKv(dictCode, true);
        for (Map<String, Object> item : dtoMapList) {
            String dictKey = UtilMap.getString(item, fieldName);
            item.put(fieldName + postfix, UtilString.isBlank(dictKey) ? null : dictKv.get(dictKey));
        }
    }

}
